﻿#region [     文件信息     ]

/*----------------------------------------------------------------
 * CLR版本：4.0.30319.42000
 * 机器名称：VAMPIREWAL
 * 公司名称：Organization
 * 命名空间：Vampirewal.Admin.PackageTool
 * 唯一标识：8abd217c-0fa4-4194-b235-820bc4f5c032
 * 文件名：MainViewModel
 * 当前用户域：VAMPIREWAL
 *
 * 创建者：Administrator
 * 电子邮箱：1425271996@qq.com
 * 创建时间：2023/3/16 13:04:12
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/

#endregion [     文件信息     ]

using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TouchSocket.Core;
using TouchSocket.Rpc.TouchRpc;
using TouchSocket.Sockets;
using Vampirewal.Admin.ShareCommon;
using Vampirewal.Admin.ShareModel.Models.Systems.AppVersion;
using Vampirewal.Admin.ShareModel.Models.Systems.Attachment;
using Vampirewal.Core;
using Vampirewal.Core.Attributes;
using Vampirewal.Core.ConfigOptions;
using Vampirewal.Core.SimpleMVVM;

namespace Vampirewal.Admin.PackageTool
{
    /// <summary>
    ///
    /// </summary>
    [VampirewalIoCRegister("Vampirewal.Admin.PackageTool.MainViewModel")]
    public partial class MainViewModel : ViewModelBase
    {
        private AppBaseOptions appbase { get; set; }
        private ServerOptions Server { get; set; }
        private PackageOptions PackageOption { get; set; }

        public MainViewModel()
        {
            //构造函数
            appbase = VampirewalCoreContext.GetInstance().GetOptions<AppBaseOptions>();
            Server = VampirewalCoreContext.GetInstance().GetOptions<ServerOptions>();
            PackageOption = VampirewalCoreContext.GetInstance().GetOptions<PackageOptions>();

            Title = appbase.AppChineseName;
            TargetPath = PackageOption.TargetPath;
            TargetFiles = PackageOption.TargetFiles;

            client = new TouchSocketConfig().SetRemoteIPHost(Server.RpcServerAddress)
                                            .SetVerifyToken("VampirewalAdmin")
                                            .SetVerifyTimeout(60000)
                                            .SetRootPath(AppDomain.CurrentDomain.BaseDirectory)
                                            .SetBufferLength(1024 * 1024)
                                            .UsePlugin()
                                            .ConfigurePlugins(a =>
                                            {
                                                a.Add<FilePlugin>();
                                            })
                                            .BuildWithTcpTouchRpcClient();

            

            

            client.Connect();

            sys_AppVersion = client.Invoke<Sys_AppVersion>("vampirewal.admin.server.rpcservices.service.systemservice.getlastversion", InvokeOption.WaitInvoke);

            New_sys_AppVersion = new Sys_AppVersion();

            if (sys_AppVersion != null)
            {
                if (File.Exists($"{AppDomain.CurrentDomain.BaseDirectory}App{sys_AppVersion.Version}.zip"))
                {
                    File.Delete($"{AppDomain.CurrentDomain.BaseDirectory}App{sys_AppVersion.Version}.zip");
                }
            }
        }

        #region [     属性     ]

        private TcpTouchRpcClient client { get; set; }

        private Sys_AppVersion _sys_AppVersion;

        public Sys_AppVersion sys_AppVersion
        {
            get { return _sys_AppVersion; }
            set { _sys_AppVersion = value; OnPropertyChanged(); }
        }

        private Sys_AppVersion new_sys_AppVersion;

        public Sys_AppVersion New_sys_AppVersion
        {
            get { return new_sys_AppVersion; }
            set { new_sys_AppVersion = value; OnPropertyChanged(); }
        }

        private string _TargetPath;

        public string TargetPath
        {
            get { return _TargetPath; }
            set { _TargetPath = value; OnPropertyChanged(); }
        }

        private List<string> _TargetFiles;

        /// <summary>
        ///
        /// </summary>
        public List<string> TargetFiles
        {
            get
            {
                return _TargetFiles;
            }
            set
            {
                _TargetFiles = value;
                OnPropertyChanged();
            }
        }

        #endregion

        [RelayCommand]
        public void SelectTargetPath()
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog()
            {
                Description = "请选择文件夹",
            };

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                TargetPath = fbd.SelectedPath;
                PackageOption.TargetPath = fbd.SelectedPath;

                VampirewalCoreContext.GetInstance().SetOptions(PackageOption);
            }
        }

        /// <summary>
        /// 选择需要打包的文件
        /// </summary>
        [RelayCommand]
        public void SelectTargetFiles()
        {
            if (string.IsNullOrEmpty(PackageOption.TargetPath))
            {
                return;
            }

            OpenFileDialog ofd = new OpenFileDialog()
            {
                Multiselect = true,
                Title = "选择打包文件",
                InitialDirectory = !string.IsNullOrEmpty(PackageOption.TargetPath) ? PackageOption.TargetPath : "",
            };

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                PackageOption.TargetFiles = ofd.FileNames.Select(s => System.IO.Path.GetFileName(s)).ToList();

                VampirewalCoreContext.GetInstance().SetOptions(PackageOption);
            }
        }

        [RelayCommand]
        public async void PackageUpload()
        {
            var TempPath = $"{AppDomain.CurrentDomain.BaseDirectory}Temp";

            Directory.CreateDirectory(TempPath);

            foreach (var item in PackageOption.TargetFiles)
            {
                string path = $"{TargetPath}\\{item}";

                File.Copy(path, $"{TempPath}\\{item}");
            }

            System.IO.Compression.ZipFile.CreateFromDirectory(TempPath, $"{AppDomain.CurrentDomain.BaseDirectory}App{New_sys_AppVersion.Version}.zip", System.IO.Compression.CompressionLevel.Fastest, false, Encoding.UTF8); //解压

            

            Directory.Delete(TempPath, true);

            Metadata metadata = new Metadata();//传递到服务器的元数据
            metadata.Add("Operation", "发布新版本");

            FileOperator fileOperator = new FileOperator()//实例化本次传输的控制器，用于获取传输进度、速度、状态等。
            {
                Flags = TransferFlags.None,//尝试断点续传，使用断点续传时，会验证MD5值
                SavePath = $@"App{New_sys_AppVersion.Version}.zip",//保存路径
                ResourcePath = $@"App{New_sys_AppVersion.Version}.zip",//请求路径
                Metadata = metadata,//传递到服务器的元数据
                //Timeout = TimeSpan.FromSeconds(60)
            };

            IResult result = await client.PushFileAsync(fileOperator);
            //var result= client.PushFile(fileOperator);

            if (result.ResultCode == ResultCode.Success)
            {
                try
                {
                    var newApp= await client.InvokeAsync<Sys_AppVersion>("vampirewal.admin.server.rpcservices.service.systemservice.createnewversion", InvokeOption.WaitInvoke, new_sys_AppVersion);

                    Sys_Attachment att = new Sys_Attachment()
                    {
                        BillId= newApp.BillId,
                        FileName= $@"App{New_sys_AppVersion.Version}.zip",
                        FilePath= $@"App{New_sys_AppVersion.Version}.zip",
                        Uploader="admin",
                        UploaderId="0",
                        ServerName= $@"App{New_sys_AppVersion.Version}.zip",
                        UploadTime=DateTime.Now,
                        FileSize="0",
                        
                    };

                    await client.InvokeAsync<bool>("vampirewal.admin.server.rpcservices.service.systemservice.addnewattachment", InvokeOption.WaitInvoke, att);

                    System.Windows.Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                File.Delete($"{AppDomain.CurrentDomain.BaseDirectory}App{New_sys_AppVersion.Version}.zip");
            }
        }
    }
}